import axios, {
  type AxiosInstance,
  type AxiosResponse,
  type InternalAxiosRequestConfig
} from 'axios'

// 定义通用响应结构
export interface ApiResponse<T = any> {
  code: number
  data: T
  message: string
}

const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
    // 可在此添加 token
    // const token = localStorage.getItem('token')
    // if (token) {
    //   config.headers.Authorization = `Bearer ${token}`
    // }
    return config
  },
  (error: any) => Promise.reject(error)
)

// 响应拦截器
service.interceptors.response.use(
  <T>(response: AxiosResponse<ApiResponse<T>>) => {
    // 根据业务逻辑调整
    if (response.data.code !== 200) {
      return Promise.reject(new Error(response.data.message || 'Error'))
    }
    return response
  },
  (error: any) => {
    // 统一错误处理
    const message = error.response?.data?.message || error.message
    console.error('请求错误:', message)
    return Promise.reject(error)
  }
)

export default service